package server.alarmThreads;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.apache.log4j.Logger;

import server.config.ServerConfig;
import server.container.EinsatzAlarm;
import server.container.NotifryInfo;
import server.db.SQL;

public class NotifryThread implements AlarmThread {

	private static Logger logger = Logger.getLogger(NotifryThread.class);

	private final String notifryUrl = "https://notifrier.appspot.com/notifry?"; // inclusieve
																				// ?

	@Override
	public void alarmiere(final EinsatzAlarm alarm) {

		new Thread(new Runnable() {

			public void run() {

				final StringBuffer builder = new StringBuffer();
				builder.append("-----Notifry alamierung gestartet-----\n");
				List<Thread> threads = new ArrayList<Thread>();
				for (final NotifryInfo info : SQL.getNotifryInfos(alarm)) {
					threads.add(new Thread(new Runnable() {

						@Override
						public void run() {

							if (!ServerConfig.getInstance().isDebug()) {
								StringBuilder b = new StringBuilder();
								Scanner scanner = null;
								try {
									b.append(notifryUrl);
									b.append("format=");
									b.append("json");

									b.append("&source=");
									b.append(URLEncoder.encode(info.getKey(), "UTF-8"));

									b.append("&title=");
									b.append(URLEncoder.encode(alarm.getEinsatzArt(), "UTF-8"));

									b.append("&message=");
									b.append(URLEncoder.encode(alarm.toString(), "UTF-8"));

									URL con = new URL(b.toString());
									scanner = new Scanner(con.openStream());
									while (scanner.hasNext()) {

										builder.append(scanner.next());
									}

								} catch (IOException e) {
									logger.error("SMS-Fehler " + b.toString(), e);
									builder.append("SMS-Fehler " + e.getMessage());
									builder.append("\n");
									e.printStackTrace();
								} finally {
									if (scanner != null) {
										scanner.close();
									}
								}

							}
						}
					}));
				}
				for (Thread t : threads) {
					t.start();
				}
				for (Thread t : threads) {
					try {
						t.join();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				builder.append("-----Nachricht ueber Notifry gesendet------");
				logger.info(builder.toString());
			}
		}).start();
	}

	/**
	 * 
	 * @param sleep
	 *            Sleep
	 */
	@SuppressWarnings("unused")
	private static void sleep(long sleep) {

		try {
			Thread.sleep(sleep);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
